
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
//注册账号
export const addRegister = async(req,res)=>{
    const { username, password } = req.body
    if(!username) return res.fail('用户名不能为空')
    if(!password) return res.fail('密码不能为空')
    try{
        const hashedPassword = await bcrypt.hash(password,10)
        const result ={
            username,
            password: hashedPassword
        }
        const addRes = await req.db.register.create({
            data: result
        })
        res.send({success: true, message:'注册成功',data:addRes })
    }catch(e){
        console.log(e)
        res.fail({success: false, message:'注册失败'})
    }
}

//登录账号
export const findLogin = async(req,res)=>{
    const { username, password } = req.body
    if(!username) return res.fail('用户名不能为空')
    if(!password) return res.fail('密码不能为空')
    try{
        const jwtSecret = process.env.JWT_SECRET;
        const where = {
            username
        }
        const user = await req.db.register.findUnique({
            where
        })
        // 验证用户是否存在且密码正确  
        if (!user || !(await bcrypt.compare(password, user.password))) {  
            return res.status(401).json({ success: false, message: '用户名或密码错误' });  
        } 
        const token = jwt.sign({ userId: user.id }, jwtSecret, { expiresIn: '1h' });
        res.send({success: true, message:'登录成功',data:{token,user} })
    }catch(e){
        console.log(e)
        res.fail({success: false, message: '登录失败'})
    }

} 

//查询一个账号上面有多少权限
export const findPermissions = async(req,res)=>{
    const { id } = req.body
    if(!id) return res.fail('id不能为空')
    try{
        const limits = await req.db.register.findMany({where:{id:id*1}})
        res.send({success: true, message:'查询成功',data:limits })
    }catch(e){
        console.log(e)
        res.fail({success: false, message:'查询失败'})
    }
}











